﻿using System;
using VegetableSale.NET.Dao;
using VegetableSale.NET.Entities;
using VegetableSale.NET.Entities.EGooden;
using VegetableSale.NET.Entities.Good;

namespace VegetableSale.NET.Services;

public class GoodService
{
    private GoodMapper goodMapper = new GoodMapper();

    public Result getGoodList(QueryDTO queryDTO)
    {
        sGoodPage sGood = new sGoodPage();
        uint pageNo = queryDTO.PageNo;
        uint pageSize = queryDTO.PageSize;
        List<Gooden> goods = goodMapper.getGoodList(queryDTO);
        List<Gooden> returnGoodens = new List<Gooden>();

        if (pageSize * pageNo - 1 >= goods.Count)
        {
            for (uint i = pageSize * (pageNo - 1); i <= goods.Count - 1; i++)
            {
                Gooden gooden = goods[(int) i];
                returnGoodens.Add(gooden);
            }
        }
        else
        {
            for (uint i = pageSize * (pageNo - 1); i <= pageSize * pageNo - 1; i++)
            {
                Gooden gooden = goods[(int) i];
                returnGoodens.Add(gooden);
            }
        }

        sGood.Records = returnGoodens;
        sGood.Pages = (int) pageNo;
        sGood.Size = pageSize;
        sGood.Total = (uint) goods.Count;

        return new Result(200, "搜索成功", sGood);
    }

    public CountResult getAllGood()
    {
        List<Gooden> goods = goodMapper.getGoodList(new QueryDTO(0, 0, ""));

        return new CountResult(0, "搜索成功", goods.Count, goods);
    }

    public Result addGood(GoodQuery goodQuery)
    {
        goodMapper.addGood(goodQuery);
        return new Result(200, "插入成功", "");
    }

    public Result deleteGood(int commid)
    {
        goodMapper.deleteGood(commid);
        return new Result(200, "删除成功", "");
    }

    public Result updateGood(Gooden gooden)
    {
        goodMapper.updateGood(gooden);
        return new Result(200, "更新成功", "");
    }

    public void updateInventory(int commid, int change, string type)
    {
        double inventory = goodMapper.getInventoryById(commid);
        double inventoryChange = 0;

        if (type.Equals("-"))
        {
            inventoryChange = inventory - change;
        }

        if (type.Equals("+"))
        {
            inventoryChange = inventory + change;
        }

        if (inventoryChange<=0)
        {
            inventoryChange = 0;
        }

        Console.WriteLine("库存更新：" + inventoryChange);

        goodMapper.updateInventory(commid, inventoryChange);
    }
}